package com.weizai.carshop.interceptor;


import com.weizai.carshop.common.context.BaseContext;
import com.weizai.carshop.common.enumeration.AppHttpCodeEnum;
import com.weizai.carshop.common.exception.BaseException;
import com.weizai.carshop.common.properties.JwtProperties;
import com.weizai.carshop.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


// 用户端拦截配置
@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    // 获取jwt配置信息
    @Autowired
    private JwtProperties jwtProperties;

    // 前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断是controller方法还是其他资源,其他资源放行
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        System.out.println("进入校验");
        // 获取请求头信息
        String token = request.getHeader(jwtProperties.getUserTokenName());

        try {
            // 校验token信息
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            // 从令牌中解析用户id
            Long userId = Long.valueOf(claims.get("userId").toString());
            // 存入用户id信息
            BaseContext.setCurrentId(userId);
            return true;
        } catch (Exception e) {
            // 输出token错误
            throw new BaseException(AppHttpCodeEnum.TOKEN_ERROR);
        }
    }

    // 后置拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        BaseContext.remove();
    }
}
